import { Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { IotCardCardEntity } from '../entity/card';

/**
 * 物联网卡信息
 */
@Provide()
export class IotCardCardService extends BaseService {
  @InjectEntityModel(IotCardCardEntity)
  iotCardCardEntity: Repository<IotCardCardEntity>;

  /**
   * 充值流量
   * @param iccid - 物联网卡的 ICCID
   * @param traffic - 需要充值的流量（单位 MB）
   */
  public async rechargeTraffic(iccid: string, traffic: number): Promise<void> {
    const iotCard = await this.iotCardCardEntity.findOneBy({
      iccid,
    });

    if (!iotCard) {
      throw new Error(`物联网卡 ${iccid} 不存在`);
    }

    /* 剩余流量（MB） */
    iotCard.remainingTraffic = Number(iotCard.remainingTraffic) + traffic;

    await this.iotCardCardEntity.save(iotCard);
  }

  /**
   * 充值短信数量
   * @param iccid - 物联网卡的 ICCID
   * @param count - 需要充值的短信数量
   */
  public async rechargeSMS(iccid: string, count: number): Promise<void> {
    const iotCard = await this.iotCardCardEntity.findOneBy({
      iccid,
    });

    if (!iotCard) {
      throw new Error(`物联网卡 ${iccid} 不存在`);
    }

    iotCard.smsUsedCount = Number(iotCard.smsUsedCount) + count;

    await this.iotCardCardEntity.save(iotCard);
  }
}
